#include "cpuranklistwidgetcomparemainwindow.h"
#include "ui_cpuranklistwidgetcomparemainwindow.h"

#include <QtWebEngineWidgets>
#include <httpclient.h>
#include <qrcutil.h>

#include <src/ui/widgets/cpurankitem.h>

CpuRankListWidgetCompareMainWindow::CpuRankListWidgetCompareMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CpuRankListWidgetCompareMainWindow)
{
    ui->setupUi(this);

//    QWebEngineView *webView = new QWebEngineView;
//    setCentralWidget(webView);

    ui->webView->load(QUrl("https://cpu.bmcx.com/6382_5493__cpu/"));

    connect(ui->webView, &QWebEngineView::loadFinished, this, [=](bool finished){
        if (finished)
            ui->webView->page()->runJavaScript(QR("://javascript.js"));

        qreal currentZoom = ui->webView->page()->zoomFactor();
        setWindowTitle(QString("currentZoom = %1  > 1.5").arg(currentZoom));

        if (currentZoom == 1) {
            ui->webView->setZoomFactor(1.5);
        }
    });

    // ----------------

    Response resp = HttpClient::instance().get("https://cpu.bmcx.com/web_system/bmcx_com_www/system/file/cpu/get_data/?lx=cpu&s=1&e=999999");
    if (resp.ok()) {

        for (const auto &var : resp.toList()) {
            auto item = new QListWidgetItem;
            auto widget = CpuRankItem::fromMap(var.toMap());

            connect(widget, &CpuRankItem::switchIdChagned, this, [=](const QString &id, bool switched){
                if (switched) {
                    m_cpuids.append(id);
                } else {
                    m_cpuids.removeAll(id);
                }
                if (not m_cpuids.isEmpty())
                    ui->webView->load(QUrl(QString("https://cpu.bmcx.com/%1__cpu/").arg(m_cpuids.join("_"))));
            });

            item->setSizeHint(widget->sizeHint());
            ui->cpu_rank_list->addItem(item);
            ui->cpu_rank_list->setItemWidget(item, widget);
        }

        // 请求完成后回到主线程更新UI
        // QMetaObject::invokeMethod(cpu_rank_model, "layoutChanged", Qt::QueuedConnection);
    }

    ui->cpu_rank_list->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);

    //
    ui->splitter->setSizes(QList<int>() << width() / 2 << width() / 2);
}

CpuRankListWidgetCompareMainWindow::~CpuRankListWidgetCompareMainWindow()
{
    delete ui;
}
